package com.mjh.zhujianju.utils;

import java.util.Map;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring容器工具类<br>
 * Spring配置文件中所定义的Bean类实现了ApplicationContextAware 接口，那么在加载Spring配置文件时，<br>
 * 会自动调用ApplicationContextAware 接口中的<br>
 * public void setApplicationContext(ApplicationContext context) throws BeansException<br>
 * 方法来设置applicationContext
 * 
 * @2016年3月22日
 */
@Component
@SuppressWarnings("unchecked")
public class SpringContextHolder implements ApplicationContextAware {
	
	private static ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		SpringContextHolder.applicationContext = applicationContext;
	}

	/**
	 *  取得存储在静态变量中的ApplicationContext
	 * @return
	 */
	public static ApplicationContext getApplicationContext() {
		return SpringContextHolder.applicationContext;
	}

	/**
	 * 从静态变量ApplicationContext中取得Bean
	 * @param name
	 * @return
	 */
	public static <T> T getBean(String name) {
		return (T)getApplicationContext().getBean(name);
	}
	
	/**
	 * 从容器中获取对象
	 * 
	 * @param clazz
	 * @return
	 */
	public static <T> T getBean(Class<T> clazz) {
		Map<String, T> beanMaps = getApplicationContext().getBeansOfType(clazz);
		if (beanMaps != null && !beanMaps.isEmpty()) {
			return (T) beanMaps.values().iterator().next();
		} else {
			return null;
		}
	}
	
	/**
	 * Spring容器中是否包含名称为name的bean
	 * 
	 * @param name
	 * @return boolean
	 */
	public static boolean containsBean(String name) {
		return getApplicationContext().containsBean(name);
	}
	
	/**
	 * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
	 * 如果与给定名字相应的bean定义没有被找到，将会抛出一个异常（NoSuchBeanDefinitionException）
	 * 
	 * @param name
	 * @return boolean
	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
	 * 
	 */
	public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
		return getApplicationContext().isSingleton(name);
	}
	
	/**
	 * @param name
	 * @return Class 注册对象的类型
	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
	 * 
	 */
	public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
		return getApplicationContext().getType(name);
	}
	
	/**
	 * 如果给定的bean名字在bean定义中有别名，则返回这些别名
	 * 
	 * @param name
	 * @return
	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
	 * 
	 */
	public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
		return getApplicationContext().getAliases(name);
	}

}
